<?php
/**
 * 买家的订单管理控制器
 * Created by PhpStorm.
 * User: Jmashimaro
 * Date: 2015/2/7
 * Time: 18:53
 */
class BuyerOrderApp extends FrontendApp {

    private $common;
    public function __construct() {
        $this->common = new CommonApp();
    }

    /**
     * 订单列表
     * @author jiayanxiu
     * @date 2015/11/10
     */
    public function index() {
        $action = '订单列表';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        if(!$user_id = $this->checkLogin()){
            $this->ajax_return(ERROR_LOGIN ,'请您登陆！');
        }
        $version = $_SERVER['HTTP_VERSION'];
//        $user_id = 101252;
//        $version = 'HeShe/1.4';

        $offset = $this->get_gp('offset', 'G');
        $size = $this->get_gp('size', 'G');

        $offset = $offset ? intval($offset) : 0;
        $size = $size ? intval($size) : 10;

        $data = array();
        $model = m('order');
        //是否是当前版本
        if ($version == IOS_VERSION) {
            $sql = "SELECT o.order_id,o.order_sn,o.status,o.order_amount,o.seller_id,o.seller_name,o.add_time,og.rec_id,
                o.buyer_id,o.buyer_name,og.goods_id,og.goods_name,og.spec_id,og.specification,og.price,og.quantity,
                og.goods_image,oe.consignee,oe.region_name,oe.address,oe.phone_mob,gs.discount_spec_price,gs.is_show_discount
                FROM `".DB_PREFIX."order` o LEFT JOIN ".DB_PREFIX."order_extm oe ON o.order_id=oe.order_id
                LEFT JOIN ".DB_PREFIX."order_goods og ON o.order_id=og.order_id LEFT JOIN ".DB_PREFIX."goods_spec gs
                ON og.spec_id=gs.spec_id WHERE o.buyer_id={$user_id} AND o.is_del=0 ORDER BY o.order_id DESC
                LIMIT {$offset},{$size}";
            $tmp = $model->getAll($sql);
            if ($tmp) {
                foreach ($tmp as $key=>$val) {
                    //获取订单售后状态
                    $sql = "SELECT `status` FROM ".DB_PREFIX."refund WHERE order_id={$val['order_id']}";
                    $refund = $model->getRow($sql);
                    $val['refund_status'] = $refund['status'] ? intval($refund['status']) : 0;
                    $val['goods_image'] = $this->common->isMySelfImage($val['goods_image'], GOODS_S_IMG);
                    //获取当前订单使用的优惠券
                    $sql = "SELECT cid FROM ".DB_PREFIX."coupons_participate WHERE uid={$user_id} AND oid='{$val['order_id']}' AND status=1";
                    $coupons = $model->getRow($sql);
                    $val['is_used'] = $coupons['cid'] ? 1 : 0;//是否使用优惠券
                    $temp[$val['order_id']][] = $val;
                    $data = array_merge(array(), $temp);
                }
            }
            $this->ajax_return(FLAG_OK, '', $data);
        } else {
            $type = $this->get_gp('type', 'G');
            if($type === 'other'){
                $conditions = ' AND `status` IN (11,20,30) ';
            }else if($type === 'finished') {
                $conditions = ' AND `status` = 40';
            }
            $conditions .= ' AND is_del=0';
            /* 查找订单 */
            $orders = $model->findAll(array(
                'conditions'    => "buyer_id= {$user_id}{$conditions}",
                'fields'        => 'this.*',
                'count'         => true,
                'limit'         => "{$offset}, {$size}",
                'order'         => 'add_time DESC',
                'include'       =>  array(
                    'has_ordergoods',       //取出商品
                ),
            ));
            $data = array();
            if ($orders) {
                foreach ((array)$orders as $key=>$value) {
                    //取出商铺Logo
                    $sql = "SELECT store_logo FROM ".DB_PREFIX."store WHERE store_id={$value['seller_id']}";
                    $value['store_logo'] = QINIU_URL.$model->getOne($sql);
                    //查找心愿单订单
                    $sql = "SELECT wish_id FROM ".DB_PREFIX."wish WHERE order_sn='{$value['order_sn']}'";
                    $wish = $model->getRow($sql);
                    if ($wish['wish_id']) {
                        $value['wish_state'] = 1;//心愿单的订单
                    } else {
                        $value['wish_state'] = 0;//不是心愿单的订单
                    }
                    $row = array();
                    foreach ((array)$value['order_goods'] as $k=>$v) {
                        $v['goods_image'] = $this->common->isMySelfImage($v['goods_image'], GOODS_S_IMG);
                        $row[] = $v;
                    }
                    unset($value['order_goods']);
                    $value['order_goods'] = $row;
                    //订单是否可以删除
                    $status = $value['status'];
                    if ($status == ORDER_FINISHED || $status == ORDER_CANCELED) {
                        $value['state'] = 1;
                    } else {
                        $value['state'] = 0;
                    }
                    $data[] = $value;
                }
            }
            $this->ajax_return(FLAG_OK,'',$data);
        }
    }


    /**
     * 订单详情
     * @author jiayanxiu
     * @date 2015/10/14
     */
    public function detail() {
        $action = '订单详情';
        setLogParameter($action);
        $this->check_method('GET');
        $user_id = $this->checkLogin();
        if(!$user_id) {
            $this->ajax_return(ERROR_LOGIN ,'请您登陆！');
        }
        $order_id = $this->get_gp('order_id', 'G');
        if(!$order_id){
            $this->ajax_return(ERROR_LOGIN ,'订单不存在！');
        }
        $order_sn = $this->get_gp('order_sn', 'G');//心愿单支付的时候用得到
        $order_id = $order_id ? intval($order_id) : 0;
        /* if($order_sn){
            $order_sn="OR o.order_sn='{$order_sn}'";
         }else{
             $order_sn="";
         }*/
        $model_order = m('order');
        $sql = "SELECT * FROM ".DB_PREFIX."order_goods WHERE order_id = '{$order_id}'";
        $good_list = $model_order->getAll($sql);
        if($good_list){
            foreach($good_list as $key=>$val){
                $val['goods_image'] = $this->common->isMySelfImage($val['goods_image'], GOODS_S_IMG);
                $good_list[$key] = $val;
            }
        }else{
            $this->ajax_return(FLAG_OK,'订单信息不存在');
        }
        $sql = "select * from ".DB_PREFIX."order o left join ".DB_PREFIX."store s on o.seller_id = s.store_id
                left join ".DB_PREFIX."order_extm oe on oe.order_id = o.order_id left join ".DB_PREFIX."shipping d
                on s.store_id = d.store_id WHERE o.buyer_id = {$user_id} AND (o.order_id = '{$order_id}' {$order_sn})";
        $store_sql = "SELECT * FROM ".DB_PREFIX."store s left join ".DB_PREFIX."order o on s.store_id = o.seller_id where o.order_id = '{$order_id}'";
        $order = $model_order->getRow($sql);
        if (!$order) {
            $this->ajax_return(FLAG_ERROR, '订单信息不存在，请您重试！');
        }
        $store = $model_order->getRow($store_sql);
        $order['region_name'] = str_replace("\t",'',$order['region_name']);        //买家地址
        $order['seller_region'] = $store['region_name'];                           //卖家地址
        $order['seller_address'] = $store['address'];                              //卖家详细地址
        $order['store_logo'] = QINIU_URL.$order['store_logo'].STORE_LOGO;
        $order['shipping_name'] = $order['shipping_name'] ? $order['shipping_name'] : '快递';
        $order["goods_list"] = $good_list;
        $this->ajax_return(FLAG_OK,'', $order);
    }

    /**
     * 确认收货
     * @author lizhuang
     * @date 2015/04/16
     */
    public function confirm(){
        $action = '确认收货';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        $order_id = $this->get_gp('order_id', 'G');
        $user_id = $this->checkLogin();
        if(!$user_id) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
        $model_order = m('order');
        $sql = "SELECT status FROM ".DB_PREFIX."order WHERE order_id = {$order_id}";
        $statue = $model_order->getOne($sql);
        if(!$statue){
            $this->ajax_return(FLAG_ERROR, '该订单不存在');
        }
        if($statue == ORDER_FINISHED){
            $this->ajax_return(FLAG_ERROR, '该商品已经确认收货');
        }
        if($statue == ORDER_ACCEPTED){
            $this->ajax_return(FLAG_ERROR, '该商品暂未发货');
        }
        //更新订单状态为ORDER_FINISHED 表示确认收货
        $data = array(
            'status'=> ORDER_FINISHED
        );
        $update = $model_order->edit("order_id = {$order_id} AND buyer_id = {$user_id}",$data);
        if($update){
            $this->ajax_return(FLAG_OK,'操作成功');
        }else{
            $this->ajax_return(FLAG_ERROR, '操作失败');
        }
    }
    /**
     * 取消订单
     * @author lizhuang
     * @date 2015/04/16
     */
    public function cancel(){
        $action = '取消订单';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        $order_id = $this->get_gp('order_id', 'G');
        $user_id = $this->checkLogin();
        if(!$user_id) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
        $model_order = m('order');
        $sql = "SELECT status FROM ".DB_PREFIX."order WHERE order_id = {$order_id}";
        $statue = $model_order->getOne($sql);
        if(!$statue){
            $this->ajax_return(FLAG_ERROR, '该订单不存在或已取消');
        }
        if($statue == ORDER_SHIPPED){
            $this->ajax_return(FLAG_ERROR, '不可以取消订单');
        }
        //更新订单状态为ORDER_CANCELED 表示取消该订单
        $data = array(
            'status'=> ORDER_CANCELED
        );
        $rs = $model_order->edit("order_id = {$order_id} AND buyer_id = {$user_id}",$data);
        if ($rs === false) {
            $this->ajax_return(FLAG_ERROR, '更新信息订单失败！');
        }
        //如果此订单使用了优惠券，则恢复优惠券
        $sql = "UPDATE ".DB_PREFIX."coupons_participate SET `status`=0,use_time=0 WHERE oid={$order_id}";
        $res = $model_order->query($sql);
        if($res === false){
            $this->ajax_return(FLAG_ERROR, '更新订单优惠券信息失败');
        }
        $this->ajax_return(FLAG_OK,'取消订单成功！');
    }

    /**
     * 删除订单
     * @author jyx
     * @date 2015/10/14
     */
    public function delete() {
        $action = '删除订单';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        $user_id = $this->checkLogin();
        if(!$user_id) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
        $order_id = $this->get_gp('order_id', 'P');
        $order_id = $order_id ? intval($order_id) : 0;
        if (!$order_id) {
            $this->ajax_return(FLAG_ERROR, '不存在的订单id！');
        }
        $model = m('order');

        $sql = "SELECT order_id FROM ".DB_PREFIX."order WHERE order_id={$order_id} AND buyer_id={$user_id} AND `status` IN (".ORDER_FINISHED.",".ORDER_CANCELED.")";
        $tmp = $model->getRow($sql);
        if ($tmp) {
            $sql = "UPDATE `".DB_PREFIX."order` SET is_del=1 WHERE order_id={$order_id} AND buyer_id={$user_id}";
            $rs = $model->query($sql);
            if ($rs === false) {
                $this->ajax_return(FLAG_ERROR, '删除订单表信息失败！');
            }
        }
        $this->ajax_return(FLAG_OK, '删除订单成功！');

    }

    /**
     * 订单列表去支付,查询商品是否还有库存
     * @author jyx
     * @date 2015/11/23 4
     */
    public function orderAlipay() {
        $action = '订单列表去支付,查询商品是否还有库存';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        if(!$user_id = $this->checkLogin()) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
        $order_id = $this->get_gp('order_id', 'G');
        if (!$order_id) {
            $this->ajax_return(FLAG_ERROR ,'订单信息不存在！');
        }
        $spec_id = $this->get_gp('spec_id', 'G');
        if (!$spec_id) {
            $this->ajax_return(FLAG_ERROR ,'数据不能为空！');
        }
        $model = m('order');
        $this->checkStock($user_id, $model, $order_id, $spec_id);
        $this->ajax_return(FLAG_OK, '');
    }

    /**
     * 查询微信支付订单
     * @author jiayanxiu
     * @date 2015/11/20
     */
    public function orderQuery() {
        $action = '查询微信支付订单';
        setLogParameter($action);
        include_once(ROOT_PATH."/includes/payments/WxPayPubHelper/WxPay.pub.config.php");
        include_once(ROOT_PATH."/includes/payments/WxPayPubHelper/WxPayPubHelper.php");
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        if(!$user_id = $this->checkLogin()) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
        $version = $_SERVER['HTTP_VERSION'];
//        $user_id = 101252;
//        $version = 'HeShe/1.4';
        $order_id = $this->get_gp('orderID', 'P');
        $wish_id = $this->get_gp('wish_id', 'P');
        $spec_id = $this->get_gp('spec_id', 'P');//商品的spec_id   1,2,45,34
        $model = m('order');
        if ($version == IOS_VERSION) {//上线之后,1.5版本开放
            $this->checkStock($user_id, $model, $order_id, $spec_id);
        }
        $sql = "SELECT o.order_sn,o.order_amount,og.goods_name FROM `".DB_PREFIX."order` o LEFT JOIN ".DB_PREFIX."order_goods og
                ON o.order_id=og.order_id WHERE o.order_id={$order_id} AND o.buyer_id={$user_id} LIMIT 1";
        $orderInfo = $model->getRow($sql);
        if (!$orderInfo) {
            $this->ajax_return(FLAG_ERROR, '订单信息不存在！');
        }
        //心愿单支付余额
        if ($wish_id) {
            $tmp = $this->wish($wish_id, $user_id);
            //需要支付余额
            if ($tmp['flag'] === false) {
                $orderInfo['order_amount'] = $tmp['price'];
            }
        }

        //重新生成订单号
        $order_sn = $this->genOrderSn();
        //更新此订单号
        $sql = "UPDATE ".DB_PREFIX."order SET order_sn='{$order_sn}' WHERE order_id={$order_id}";
        $flag = $model->query($sql);
        if ($flag === false) {
            $this->ajax_return(FLAG_OK, '更新订单号失败！');
        }
        //微信统一下单
        $input = new UnifiedOrder_pub();
        //$input->setParameter('body', addslashes(mb_substr($orderInfo['goods_name'],0,8)));
        $input->setParameter('body',"He She Trends商城购物");
        $input->setParameter('out_trade_no', $order_sn);
        $input->setParameter('total_fee', floatval($orderInfo['order_amount'] * 100));
        $input->setParameter('time_start', date("YmdHis"));
        $input->setParameter('time_expire', date("YmdHis", time() + 600));
        $input->setParameter('notify_url', WxPayConf_pub::NOTIFY_URL);
        $input->setParameter('trade_type', 'APP');
        $row = $input->getPrepayId();
        if ($row['return_code'] == 'SUCCESS' && $row['result_code'] == 'FAIL') {
            $this->ajax_return(FLAG_ERROR, $row['err_code_des']);
        } elseif ($row['return_code'] == 'SUCCESS' && $row['result_code'] == 'SUCCESS') {
            $res['timestamp']   = time();
            $res['appid']       = $row['appid'];
            $res['partnerid']   = $row['mch_id'];
            $res['noncestr']    = $row['nonce_str'];
            $res['prepayid']    = $row['prepay_id'];
            $res['package']     = 'Sign=WXPay';
            $res['sign'] = $input->getSign($res);
            $this->ajax_return(FLAG_OK, '', $res);
        } else {
            $this->ajax_return(FLAG_ERROR, '微信支付失败！');
        }
    }

    /**
     * 检测商品库存是否充足
     * @param $user_id
     * @param $model
     * @param $order_id
     * @param $spec_id
     * @return bool
     * @author jyx
     * @date 2015/11/23
     */
    private function checkStock($user_id, $model, $order_id, $spec_id) {
        //获取订单中商品的数量
        $sql = "SELECT SUM(og.quantity) AS quantity FROM `".DB_PREFIX."order` o LEFT JOIN ".DB_PREFIX."order_goods og
            ON o.order_id=og.order_id WHERE og.spec_id IN ({$spec_id}) AND o.order_id={$order_id} AND o.buyer_id={$user_id}";
        $orderCount = $model->getRow($sql);
        $sql = "SELECT SUM(stock) AS stock FROM ".DB_PREFIX."goods_spec WHERE spec_id IN ({$spec_id})";
        $goodsCount = $model->getRow($sql);
        if ($orderCount['quantity'] > $goodsCount['stock']) {
            $this->ajax_return(FLAG_ERROR ,'当前商品库存不足！');
        }
        return true;
    }

    /**
     * 申请退款接口
     * @author jyx
     * @date 2015/11/16
     */
    public function refund() {
        $action = '申请退款接口';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        if (!$user_id = $this->checkLogin()) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
        $type = $this->get_gp('type', 'P');//退货类型
        $rec_id   = $this->get_gp('rec_id', 'P');//订单商品的id
        $buyer_desc = $this->get_gp('buyer_desc', 'P');//买家留言 123
        $rec_id = $rec_id ? intval($rec_id) : 0;
        if (!$rec_id) {
            $this->ajax_return(FLAG_ERROR, '订单商品的id不存在！');
        }
        if (!in_array($type, array(1,2,3))) {
            $this->ajax_return(FLAG_ERROR, '退货类型不正确！');
        }
        $model = m('order');
        $model->begin();
        //获取订单信息
        $sql = "SELECT og.rec_id,og.order_id,og.goods_id,og.spec_id,og.quantity,o.order_amount FROM ".DB_PREFIX."order_goods og
            LEFT JOIN `".DB_PREFIX."order` o ON og.order_id=o.order_id WHERE og.rec_id={$rec_id} AND o.buyer_id={$user_id} LIMIT 1";
        $info = $model->getRow($sql);
        if (!$info) {
            $this->ajax_return(FLAG_ERROR, '订单信息不存在!');
        }
        $time = time();
        //插入退货的信息
        $sql = "INSERT INTO ".DB_PREFIX."refund (user_id,order_id,goods_id,spec_id,goods_rec_id,goods_number,money_refund,
            `status`,`type`,buyer_desc,add_time) VALUES ({$user_id},{$info['order_id']},{$info['goods_id']},{$info['spec_id']},
            {$info['rec_id']},{$info['quantity']},{$info['order_amount']},1,{$type},'{$buyer_desc}',{$time})";
        $rs = $model->query($sql);
        if ($rs === false) {
            $this->ajax_return(FLAG_ERROR, '申请退款失败!');
        }
        $model->commit();
        $this->ajax_return(FLAG_OK, '');
    }



    /**
     * 计算出是否要支付金额
     * @param $wish_id
     * @param $user_id
     * @return bool
     * @author jyx
     * @date 2015/07/30
     */
    private function wish($wish_id, $user_id) {
        $model = m('wish');
        //查询出商品的总金额
        $sql = "SELECT w.wish_id,w.goods_id,w.spec_id,gs.price FROM ".DB_PREFIX."wish w LEFT JOIN ".DB_PREFIX."goods_spec gs
				ON w.spec_id=gs.spec_id WHERE w.wish_id={$wish_id} AND user_id={$user_id}";
        $tmp = $model->getRow($sql);
        //查询出捐赠的总金额
        $sql = "SELECT SUM(donate_price) AS total_price FROM ".DB_PREFIX."wish_log WHERE wish_id={$wish_id} AND `status`=1";
        $temp = $model->getRow($sql);
        $price = floatval($tmp['price'] - $temp['total_price']);
        if ($price < 0 ) {
            $price = 0;
        }
        //如果金额相等，则去生成一条订单，入库,不需要支付！
        if ($temp['total_price'] == $tmp['price'] || $price == 0) {
            $tmp['flag'] = true;
        } else {
            $tmp['flag'] = false;
            $tmp['price'] = $price;
        }
        return $tmp;
    }


    /**
     * 在未付款订单列表检测此订单是否是心愿订单
     * @author jiayanxiu
     * @date 2015/06/25
     */
    public function wishQuery() {
        $action = '在未付款订单列表检测此订单是否是心愿订单';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR ,'非法的请求！');
        }
        $user_id = $this->checkLogin();
        if (!$user_id) {
            $this->ajax_return(ERROR_LOGIN ,'请您登陆！');
        }
        $order_id = $this->get_gp('order_id', 'P');
        $order_id = $order_id ? intval($order_id) : 0;
        if (!$order_id) {
            $this->ajax_return(FLAG_ERROR ,'订单号不存在！');
        }
        $model = m('order');
        $sql = "SELECT o.order_amount,o.order_sn,w.wish_id FROM ".DB_PREFIX."order o LEFT JOIN ".DB_PREFIX."wish w
                ON o.order_sn=w.order_sn WHERE o.order_id='{$order_id}' AND o.buyer_id={$user_id}";
        $row = $model->getRow($sql);
        if ($row['wish_id']) {
            $sql = "SELECT SUM(donate_price) AS total_price FROM ".DB_PREFIX."wish_log WHERE wish_id='{$row['wish_id']}' AND `status`=1";
            $tmp = $model->getRow($sql);
            $data['order_amount'] = $row['order_amount'] - $tmp['total_price'];
            $data['order_amount'] = floatval($data['order_amount']);
        } else {
            $data['order_amount'] = $row['order_amount'];
        }
        $data['order_sn'] = $row['order_sn'];
        $data['wish_id'] = $row['wish_id'];
        $this->ajax_return(FLAG_OK, '', $data);
    }


    /**
     * 生成订单号
     * @return string
     * @author jiayanxiu
     * @date 2015/10/26
     */
    private function genOrderSn() {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        $timestamp = gmtime();
        $y = date('y', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $model = m('order');
        $sql = "SELECT order_id FROM `".DB_PREFIX."order` WHERE order_sn='{$order_sn}' LIMIT 1";
        $orders = $model->getRow($sql);
        if (empty($orders)) {
            /* 否则就使用这个订单号 */
            return $order_sn;
        }
        /* 如果有重复的，则重新生成 */
        return $this->genOrderSn();
    }


}